<template>
    <div>

        <!-- 如果有定位数据，则显示定位信息 -->
        <div v-if="locationData">
            <p @click="JumpCity">
                <img src="../../img/定位.png" alt=""><span @click="showCityList = true">
                    {{ city == null ? locationData.city : city }}
                </span>
            </p>
        </div>
        <!-- 否则显示加载中 -->
        <div v-else>
            <p>加载中...</p>
        </div>
    </div>
</template>

<script lang="ts">
// @ts-ignore
import { defineComponent, ref, onMounted } from 'vue';
import axios from 'axios';
import { cityList } from '../cities';
import router from '../../router';
interface LocationData {
    ip: string;
    city: string;
    province: string;
    district: string;
}
export default defineComponent({
    name: 'IpLocator',
    setup() {
        // 存储定位数据
        const locationData = ref<LocationData | null>(null);
        // 是否显示城市列表的状态
        const showCityList = ref(false);
        // 获取定位数据的方法
        const fetchLocationData = async () => {
            try {
                const ip = '124.127.222.50'; // 目标IP地址, 可替换为动态的用户IP
                const apiKey = 'be64c3933f21b1cf456735c678152f48'; // 替换为你自己的高德API密钥
                const url = `https://restapi.amap.com/v3/ip?ip=${ip}&output=xml&key=${apiKey}`;
                // 发送请求并打印响应数据
                const response = await axios.get(url);
                // console.log('API Response:', response.data);
                // 检查返回的XML数据
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(response.data, 'application/xml');
                // 输出解析后的 XML
                // console.log('Parsed XML:', xmlDoc);
                // 解析 XML 数据
                if (xmlDoc.getElementsByTagName('parsererror').length > 0) {
                    console.error('XML 解析错误');
                } else {
                    // 获取所需的数据
                    const province = xmlDoc.getElementsByTagName('province')[0].textContent;
                    const city = xmlDoc.getElementsByTagName('city')[0].textContent;
                    // 整理数据并赋值给locationData
                    locationData.value = {
                        ip: ip,
                        city: city,
                        province: province,
                        district: '' // 这里假设从当前数据中无法直接获取district信息，可根据实际情况补充获取方式
                    };
                }
            } catch (error) {
                console.error('定位请求失败:', error);
            }
        };

        // 选择城市的方法
        const selectCity = (selectedCity: string) => {
            locationData.value!.city = selectedCity;
            showCityList.value = false;
        };

        // 在组件挂载后获取数据
        onMounted(() => {
            fetchLocationData();
        });
        const JumpCity = () => {
            router.push('/homeCity')
        }

        const city = localStorage.getItem('city')

        return {
            locationData,
            showCityList,
            cityList,
            selectCity,
            JumpCity,
            city
        };
    }
});
</script>

<style scoped lang="scss">
h1 {
    font-size: .24rem;
    margin-bottom: .2rem;
}

p {
    font-size: .12rem;

    img {
        width: .2rem;
        height: .2rem;
    }
}

/* 城市列表弹出框样式 */
.city-list-popup {
    height: 2rem;
    overflow: scroll;
    position: absolute;
    background-color: white;
    border: .01rem solid #ccc;
    padding: .1rem;
    z-index: 1;
}

.city-list-popup ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.city-list-popup li {
    cursor: pointer;
    padding: .05rem;
}
</style>